package stone926.mods.more_enchantments.items;

import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.mob.MobEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.particle.ParticleTypes;
import net.minecraft.predicate.entity.EntityPredicates;
import net.minecraft.server.world.ServerWorld;
import net.minecraft.util.Hand;
import net.minecraft.util.TypedActionResult;
import net.minecraft.util.math.Box;
import net.minecraft.world.World;
import stone926.mods.more_enchantments.MoreEnchantmentsMod;
import stone926.mods.more_enchantments.enchantments.CooldownShorterEnchantment;
import stone926.mods.more_enchantments.interfaces.IMobEntity;
import stone926.mods.more_enchantments.util.RandomUtil;

import java.util.List;

public class CompressedSpiritualStuffsItem extends Item {

  public CompressedSpiritualStuffsItem(Settings settings) {
    super(settings);
  }

  @Override
  public TypedActionResult<ItemStack> use(World world, PlayerEntity user, Hand hand) {
    if (!user.getItemCooldownManager().isCoolingDown(MoreEnchantmentsMod.COMPRESSED_SPIRITUAL_STUFFS)) {
      List<MobEntity> mobs = world.getEntitiesByClass(
        MobEntity.class, Box.from(user.getPos()).expand(RandomUtil.nextInt(10, 18, user.getRandom())),
        EntityPredicates.VALID_LIVING_ENTITY
      );
      if (!mobs.isEmpty()) {
        int i = RandomUtil.nextInt(80, 100, user.getRandom());
        mobs.forEach(mob -> ((IMobEntity) mob).setAiDisableTicks(i));
        if (world instanceof ServerWorld server) {
          server.spawnParticles(
            ParticleTypes.CLOUD,
            user.getX(), user.getY() + 2.5, user.getZ(),
            80, 0.3, 1, 0.3, 0.2
          );
        }
        int lvl = EnchantmentHelper.getLevel(MoreEnchantmentsMod.COOLDOWN_SHORTER, user.getStackInHand(hand));
        user.getItemCooldownManager().set(
          MoreEnchantmentsMod.COMPRESSED_SPIRITUAL_STUFFS,
          (int) (RandomUtil.nextInt(100, 140, user.getRandom()) * CooldownShorterEnchantment.getShorterCooldown(lvl))
        );
        if (!user.getAbilities().creativeMode)
          RandomUtil.runIfPossible(0.05, user.getRandom(), () -> user.getStackInHand(hand).decrement(1));
        return TypedActionResult.success(user.getStackInHand(hand));
      }
    }
    return TypedActionResult.pass(user.getStackInHand(hand));
  }

}
